<?php

namespace App\Models\Admin;

use App\Log\CompanyMenuLog;
use DB,Auth;

class Menu extends Base
{
    const OPERATE_PID = 1;
    const MODEL = 'menu';

    protected $table = 'menu';
    public $timestamps = false;
    protected $guarded = [];


    /**
     * 表内关联
     * 获取下级菜单
     */
    public function selfNext()
    {
        return $this->hasMany($this,'id');
    }
    public function selfLast()
    {
        return $this->belongsTo($this,'pid');
    }

    public function product()
    {
        return $this->belongsTo(AdminProduct::class,'type','id');
    }

    /**
     * 根据类型，返回菜单列表,只返回一、二级
     */
    public static function getListByTypeBase($type=0){
        $nav = self::where('type',$type)
            ->select(self::getField())
            ->orderBy('ordid','asc')
            ->get();
        if($nav->isEmpty())
        {
            return $nav;
        }
        $nav=$nav->groupBy('pid');
        //获得一级菜单
        $one = $nav[0];
        //移除一级菜单
        unset($nav[0]);
        $one = $one->transform(function ($item, $key) use($nav){
            if (isset($nav[$item->id]))
            {
                $item->selfNext = $nav[$item->id];
            }
            else
            {
                $item->selfNext =[];
            }
            return $item;
        });
        return $one;
    }

    public static function getListByPid($data)
    {
        $where=[];
        if(isset($data['type']))
        {
            $where[]=['type',$data['type']];
        }
        if(isset($data['pid']))
        {
            $where[]=['pid',$data['pid']];
        }
        $list = self::where($where)
            ->select(self::getField())
            ->orderBy('ordid','asc')
            ->get();
        return $list;
    }

    //返回所有级别
    public static function getListByTypeAll($type=0){
        $list = self::where('type',$type)
            ->orderBy('pid','asc')
            ->orderBy('ordid','asc')
//            ->select(self::getField())
            ->get();
        if(empty($list))
        {
            return $list;
        }
        $list=self::generateTree($list);
        return $list;

    }

    public static function getField()
    {
        return [
            'id','name','short_name','pid','ordid','display','controller','route','action','type'
        ];
    }

    public static function getDetaiById($id)
    {
        $info = self::where('id',$id)
            ->with([
                'product:id,name'
            ])
//        ->select(self::getField())
            ->first();
        if($info->pid==0)
        {
            $info->p_name='根菜单';
        }
        else
        {
            $info->p_name=self::where('id',$info->pid)->value('name');
        }
        return $info;
    }

    //根据子id，获取各级的父级菜单
    public static function getPMenuById ($id)
    {
        $path_arr=self::getPathById($id);
        if(empty($path_arr))
        {
            return [];
        }
        $type=self::where('id',$id)->value('type');
        $type=is_null($type)?0:$type;
        $menu_list_1=self::getMenuLevel($type);
        $pid=end($path_arr);
        array_pop($path_arr);
        $data_res['menu_list_1']=$menu_list_1;
        if(empty($path_arr))
        {
            return $data_res;
        }
        $menu_list_2=self::getMenuLevel($type,$pid);
        $data_res['menu_list_2']=$menu_list_2;
        $pid=end($path_arr);
        array_pop($path_arr);
        if(empty($path_arr))
        {
            return $data_res;
        }
        $menu_list_3=self::getMenuLevel($type,$pid);
        $data_res['menu_list_3']=$menu_list_3;
        return $data_res;
    }

    public static function getMenuLevel($type=1,$pid=0)
    {
        $where=[
            'pid'=>$pid,
            'type'=>$type,
        ];
        $list=self::getListByPid($where)->toArray();
        return $list;
    }

    //获取所有类型的一二级菜单
    public static function getMenuListAll()
    {
        //获取类型
        $type_list=CompanyType::with(['product'])->get();
        $type_list->transform(function ($it,$V)
        {
            $it->product->transform(function ($i)
            {
                //根据id，获取到菜单
                $i->selfNext=Menu::getListByTypeBase($i->id);
                $data_index=[
                    'id'=>0,
                    'name'=>'首页',
                    'pid'=>0,
                    'type'=>$i->id,
                ];
                $i->selfNext=$i->selfNext->prepend($data_index);
                return $i;
            });
            $it->selfNext=$it->product;
            unset($it->product);
            return $it;
        });
        return $type_list;
    }

    public static function addLog($pre,$next,$type,$method='')
    {
        $info = AdminOperateModule::where('pid',self::OPERATE_PID)->where('type',$type)->where('model',self::MODEL)->when($method,function ($query)use ($method){
            $query->where('method',$method);
        })->first();
        if (!empty($info)){
            $adminLog = new CompanyMenuLog($pre,$next,$info);
            $adminLog->addLog();
        }
    }
}
